<template>
  <div>
    <!-- 三级分类组件 -->
    <Category :scene="scene"></Category>
    <!-- 底部静态页面 -->
    <el-card shadow="always" :body-style="{ padding: '20px' }" style="margin: 10px 0">
      <div v-show="scene==0">
        <el-button
          type="primary"
          size="default"
          :icon="Plus"
          @click="addAttr"
          :disabled="!categoryStore.c3id"
          >添加属性</el-button
        >
        <el-table border stripe style="margin: 10px 0" :data="attrList">
          <el-table-column
            label="序号"
            width="80px"
            align="center"
            type="index"
          ></el-table-column>
          <el-table-column
            label="属性名称"
            width="150px"
            prop="attrName"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column label="属性值列表">
            <template #="{ row, $index }">
              <el-tag
                style="margin: 0px 3px"
                class="ml-2"
                type="success"
                v-for="(attrVal, index) in row.attrValueList"
                :key="attrVal.id"
                >{{ attrVal.valueName }}</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150px">
            <template #="{ row, $index }">
              <!-- 修改按钮 -->
              <el-button type="primary" size="small" :icon="Edit" @click="updateAttr(row)"></el-button>
              <!-- 删除按钮 -->
              <el-button type="danger" size="small" :icon="Delete" @click="removeAttr(row)" ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-show="scene==1">
        <!-- 添加/修改属性 -->
        <el-form ref="form" :inline="true" >
            <el-form-item label="属性名" >
                <!-- 收集属性名字 -->
                <el-input v-model="attrParams.attrName"  placeholder="请你输入属性的名字" clearable ></el-input>
            </el-form-item>
        </el-form>
        <el-button type="primary" @click="addAttrValue" :icon="Plus" :disabled="!attrParams.attrName">添加属性值</el-button>
        <el-button @click="cancel">取消</el-button>
        <!-- 展示表格数据 -->
        <el-table border stripe style="margin:10px 0" :data="attrParams.attrValueList">
            <el-table-column label="序号" width="80px" align="center" type="index" ></el-table-column>
            <el-table-column label="属性值名称" >
                <template #="{row,$index}">
                    <el-input :ref="(vc)=>{inputArr[$index] = vc}"  @blur="toLook(row, $index)" v-if="row.flag" v-model="row.valueName" placeholder="请你输入属性值"></el-input>
                    <div v-else @click="toEdit(row, $index)">{{row.valueName}}</div>
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template #="{row,$index}">
                    <el-button type="danger" :icon="Delete" size="small" @click="attrParams.attrValueList.splice($index,1)"></el-button>
                    
                </template>
            </el-table-column>
        </el-table>
        <el-button type="primary" :disabled="attrParams.attrValueList.length>0?false:true" @click="save" >保存</el-button>
        <el-button @click="cancel">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
//引入组合式APIwatch
import { watch, ref, reactive, nextTick, onUnmounted } from "vue";
//引入lodash里面cloneDepp---深拷贝
import _ from "lodash";

//引入数据类型
import type {attrResponseData,attrModel,attrValueModel} from '@/api/product/attr/model/attr'


import { ElMessage } from "element-plus";
import {
  Check,
  Delete,
  Edit,
  Message,
  Search,
  Star,
  Plus,
  UploadFilled,
} from "@element-plus/icons-vue";
//引入请求函数
import {
  reqAttrList,
  reqAddOrUpdateAttr,
  reqDeleteAttr,
} from "@/api/product/attr/attr";
// 引入仓库
import { useCategoryStore } from "@/stores/category";
// 调用仓库
let categoryStore = useCategoryStore();
// 定义存储平台属性的数据
let attrList = ref<attrResponseData>([]);
// 定义响应式变量控制场景切换
let scene = ref<number>(0)
// 定义数组ref类型数据,将来存储el-input组件的实例
let inputArr = ref<any>([])
// 定义将来添加或修改属性的参数
let attrParams = reactive<attrModel>({ 
  attrName: "",
  categoryId:'',
  categoryLevel: 3,
  attrValueList: [],
})


//监听三级分类的ID变化，如果发生变化需要发请求
watch(
  () => categoryStore.c3id,
  () => {
    // 如果三级分类的id为空,则直接返回
    if (categoryStore.c3id == "") return;
    // 获取商品属性
    getAttrList();
  }
);

// 获取商品属性请求封装成一个函数
const getAttrList = async () => {
  //  发送请求
  let result = await reqAttrList(
    categoryStore.c1id,
    categoryStore.c2id,
    categoryStore.c3id
  );
  //   获取并存储商品属性数据
   attrList.value = result;
};

// 点击添加属性按钮回调
const addAttr = ()=>{
    // 清除要带给服务器的数据
    Object.assign(attrParams,{
    attrName: "",
    //每一次进入到添加|修改属性的时候，清空数据|同时把三级分类ID收集到
    categoryId: categoryStore.c3id, 
    categoryLevel: 3,
    attrValueList: [],
  })
    scene.value=1
  
}

// 点击两个取消按钮切换场景
const cancel = ()=>{
    scene.value = 0
}

// 点击添加属性值的按钮回调
const addAttrValue = ()=>{
// 向属性值数组添加元素
attrParams.attrValueList.push({
    valueName:'',
    flag:true
})
  // 数组最后一个聚焦
  nextTick(()=>{
        inputArr.value[attrParams.attrValueList.length-1].focus()
    })
}

// input失去焦点回调,变为查看模式
const toLook = (row:attrValueModel,$index:number)=>{
    // 属性值为空的时候,删除这个非法属性值
    if(row.valueName.trim()==''){
       ElMessage({
        type:'error',
        message:'不能为空'
       })
    //    删除当前非法属性值
    attrParams.attrValueList.splice($index,1)
     return 
    }

    // 属性值重名
    let repet =  attrParams.attrValueList.find((item)=>{
        // 扣除自身
          if(row!=item){
            return row.valueName === item.valueName
          }
    })

    // 如果出现重复
    if(repet){
        ElMessage({
        type:'error',
        message:'不能存在一样的值' 
        })
    // 删除当前非法属性值对象
    attrParams.attrValueList.splice($index,1)
    return
    }
     row.flag=false
}
// div点击事件回调,变为编辑模式
const toEdit = (row:attrValueModel,$index:number)=>{
    row.flag=true
    // 点击div切换显示el-inpt,需要聚焦
    nextTick(()=>{
        inputArr.value[$index].focus()
    })
}

// 点击保存按钮的回调,添加属性请求发送
const save = ()=>{
    attrParams.attrValueList.forEach(async (item)=>{
        if(item.hasOwnProperty('flag')){
             delete item.flag
        }

        try {
            let result = await reqAddOrUpdateAttr(attrParams)
            // 切换场景
            scene.value = 0
            ElMessage({
                type:'success',
                message: attrParams.id ? "修改成功" : "添加成功",
            })
              //获取全部最新的属性的数据
          getAttrList();

        } catch (error) {
            ElMessage({
      type: "success",
      message: attrParams.id ? "修改失败" : "添加失败",
    });
        }
   
    })
}

// 修改按钮的回调
const updateAttr = (row:attrModel)=>{
//    切换场景
scene.value=1
// 深拷贝获取已有数据
Object.assign(attrParams, _.cloneDeep(row));
}

// 删除按钮的回调
const removeAttr =async (row:attrModel)=>{
    try {
    //删除已有属性成功
    await reqDeleteAttr(row.id);
    //提示信息
    ElMessage({
      type: "success",
      message: `删除${row.attrName}成功`,
       duration:500,//约束提示信息的事件
    });
    //再次获取最新的属性的数据
    getAttrList();
  } catch (error) {
    // 失败提示信息
    ElMessage({
      type: "error",
      message: `删除${row.attrName}失败`,
      duration:500
    });
  }
}

// 销毁钩子  跳转路由时,组件销毁,要清空仓库数据
onUnmounted(() => {
  categoryStore.c1id=''
  categoryStore.c2id=''
  categoryStore.c3id=''
  categoryStore.c1List=[]
  categoryStore.c2List=[]
  categoryStore.c3List=[]
})
</script>

<style scoped></style>
